using SqlSugar;

namespace iPanel.DataProvider;
public class TelemetryDbContext
{
    /// <summary>
    /// 获取用于与数据库进行交互的 SqlSugar 客户端实例。
    /// 该实例负责执行数据库操作，如查询、插入、更新和删除等。
    /// 在构造函数中进行初始化，并配置了数据库连接字符串、数据库类型和自动关闭连接等选项。
    /// </summary>
    public SqlSugarScope Db { get; }

    public TelemetryDbContext()
    {
        //Db = new SqlSugarClient(new ConnectionConfig
        //{
        //    ConnectionString = "Data Source=telemetry.db",
        //    DbType = DbType.Sqlite,
        //    IsAutoCloseConnection = true
        //});
        Db = new SqlSugarScope(new ConnectionConfig()
        {
            ConnectionString = "Data Source=telemetry.db",//连接符字串
            DbType = DbType.Sqlite,//数据库类型
            IsAutoCloseConnection = true //不设成true要手动close
        }, db =>
        {
            try
            {
                // 设置 WAL 模式
                db.Ado.ExecuteCommand("PRAGMA journal_mode=WAL;PRAGMA wal_autocheckpoint=1000;PRAGMA page_size = 4096;PRAGMA synchronous = OFF;");
                //db.Ado.ExecuteCommand("PRAGMA wal_autocheckpoint=1000;");
                //// 设置页面大小
                //db.Ado.ExecuteCommand("PRAGMA page_size = 4096;");
                //// 设置同步策略为 OFF
                //db.Ado.ExecuteCommand("PRAGMA synchronous = OFF;");

                //Console.WriteLine("已成功设置 SQLite PRAGMA 配置");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"设置 SQLite PRAGMA 配置时出错: {ex.Message}");
            }
        });

        // 建表
        Db.CodeFirst.InitTables(
            typeof(OtlpApplicationEntity),
            typeof(OtlpLogEntryEntity),
            typeof(OtlpLogPropertyKeysEntity),

            typeof(OtlpTraceEntity),
            typeof(OtlpTracePropertyKeysEntity),
            typeof(OtlpSpanEntity),
            typeof(OtlpSpanLinkEntity),
            typeof(OtlpSpanEventEntity),

            typeof(OtlpInstrumentKeyEntity),
            typeof(OtlpInstrumentEntity),
            typeof(OtlpInstrumentSummaryEntity),
            typeof(OtlpMeterEntity),
            typeof(OtlpResourceEntity),
            typeof(OtlpNodeMapApplicationEntity)
        );
    }
}
